package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.AccumulatorProduct;
import com.apes.autoparts.product.model.BrandProduct;
import com.apes.autoparts.product.model.TyreProduct;
import com.apes.autoparts.product.repository.AccumulatorProductRepository;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：蓄电池标准商品服务类
 *
 * @ClassName AccumulatorProductService
 * @Description 描述
 * @Author lilong
 * @Date 2022/10/27 11:30
 * @Version 1.0
 */
@Service
public class AccumulatorProductService {

    @Autowired
    private AccumulatorProductRepository accumulatorProductRepository;

    @Autowired
    private ProductDao productDao;


    /**
     * 动态条件查询
     * @param request
     */
    public Map conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();
        String brand = jo.getString("brand");
        String pn = jo.getString("pn");
        String type = jo.getString("type");
        int page = jo.getInteger("page") < 0 || jo.getInteger("page")==null ? 0 : jo.getInteger("page");
        if (Objects.isNull(brand) && Objects.isNull(pn) && Objects.isNull(type)) {
            Page<AccumulatorProduct> accumulatorPage = accumulatorProductRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", accumulatorPage.getContent(), "page", page, "sum", accumulatorPage.getTotalPages());
        }
        Page<AccumulatorProduct> accumulatorPage = accumulatorProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("brand", "EQ", brand,
                "pn", "EQ", pn,
                "type", "EQ", type),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", accumulatorPage.getContent(), "page", page, "sum", accumulatorPage.getTotalPages());
    }
    /**
     * 放弃编辑回显当前数据
     * @param request
     * @return
     */
    public Map accumulatorProductFindOne(SimpleRequest request){
        List<AccumulatorProduct> list = request.getA("accumulatorProductItems", AccumulatorProduct.class);
        return MapUtil.mapper("accumulatorProductItems",list);
    }



    /**
     * 批量更新原厂标准商品
     *
     */
    public Map edit(SimpleRequest request){
        //新增和修改
        List<AccumulatorProduct> accumulatorList = request.getA("accumulatorProductItems", AccumulatorProduct.class);

        //根据id判断新增
        List<AccumulatorProduct> newAccumulatorProduct = accumulatorList.stream().filter(accumulator -> Objects.isNull(accumulator.getId()) || "".equals(accumulator.getId()))
                .collect(Collectors.toList());

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))){
            List<AccumulatorProduct> delAccumulator = request.getA("del", AccumulatorProduct.class);
            delAccumulator.forEach(accumulator -> {
                if (Objects.nonNull(accumulator.getId())){
                    accumulatorProductRepository.delete(accumulator);
                }
            });
        }
            productDao.accumulatorProductInsert(newAccumulatorProduct);

        return  MapUtil.mapper("accumulatorProductItems", newAccumulatorProduct);

    }


    /**
     * 定制导入轮胎标准商品
     * @param request
     * @return
     */
    public JSONObject importAccumulatorProduct(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();
        JSONArray titleArray = new JSONArray(14);
        //titleArray.add("编号");
        titleArray.add("品牌");
        titleArray.add("零件号");
        titleArray.add("单位");
        titleArray.add("国际标号");
        titleArray.add("参考号");
        titleArray.add("类型");
        titleArray.add("系列");
        titleArray.add("额定容量");
        titleArray.add("额定电压");
        titleArray.add("尺寸");
        titleArray.add("端子");
        titleArray.add("冷启动电流");
        titleArray.add("产品描述");
        titleArray.add("条形码");
        titleArray.add("ERP商品编码");
        titleColumnArray.add(titleArray);

        List<AccumulatorProduct> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            if (((JSONArray) importDataValueArray.get(0)).size() != 15) throw new RuntimeException("导入模板错误，请检查文件并重新上传！");
            importDataValueArray.parallelStream().forEach(item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() == 0) return;

                String brand = "";
                String pn = "";
                String unit = "";
                String grade = "";
                String reference = "";
                String type = "";
                String series = "";
                String capacity = "";
                String voltage = "";
                String sizes = "";
                String terminal = "";
                String electricity = "";
                String describe = "";
                String barCode = "";
                String ERPProductId = "";

                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0: brand = iValueArray.getString(0);
                             break;
                        case 1: pn = iValueArray.getString(1);
                            break;
                        case 2: unit = iValueArray.getString(2);
                            break;
                        case 3: grade = iValueArray.getString(3);
                            break;
                        case 4: reference = iValueArray.getString(4);
                            break;
                        case 5: type = iValueArray.getString(5);
                            break;
                        case 6: series = iValueArray.getString(6);
                            break;
                        case 7: capacity = iValueArray.getString(7);
                            break;
                        case 8: voltage = iValueArray.getString(8);
                            break;
                        case 9: sizes = iValueArray.getString(9);
                            break;
                        case 10: terminal = iValueArray.getString(10);
                            break;
                        case 11: electricity = iValueArray.getString(11);
                            break;
                        case 12: describe = iValueArray.getString(12);
                            break;
                        case 13: barCode = iValueArray.getString(13);
                            break;
                        case 14: ERPProductId = iValueArray.getString(14);
                            break;
                    }
                }
                //跳过首行标题行
                if ( "零件名称".equals(pn) || "类型".equals(type)) return;
                //if (!stringHashSet.add(brand +grade+reference)) throw new RuntimeException("导入重复数据，请重新导入！");
                AccumulatorProduct accumulatorProduct = new AccumulatorProduct();
                accumulatorProduct.setBrand(brand);
                accumulatorProduct.setPn(pn);
                accumulatorProduct.setUnit(unit);
                accumulatorProduct.setGrade(grade);
                accumulatorProduct.setReference(reference);
                accumulatorProduct.setType(type);
                accumulatorProduct.setSeries(series);
                if(!"".equals(capacity)){
                    accumulatorProduct.setCapacity(Double.parseDouble(capacity));
                }
                if(!"".equals(voltage)){
                    accumulatorProduct.setVoltage(Double.parseDouble(voltage));
                }
                accumulatorProduct.setSizes(sizes);
                accumulatorProduct.setTerminal(terminal);
                accumulatorProduct.setElectricity(electricity);
                accumulatorProduct.setDescribe(describe);
                accumulatorProduct.setBarCode(barCode);
                accumulatorProduct.setERPProductId(ERPProductId);
                dataList.add(accumulatorProduct);
            });
        });
        productDao.accumulatorProductInsert(dataList);
        return key.get();
    }

    /**
     * 下载
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String pn = condition.getString("pn");
        String brand = condition.getString("brand");
        String type = condition.getString("type");
        if("".equals(pn)){
            pn=null;
        }
        if("".equals(brand)){
            brand=null;
        }
        if("".equals(type)){
            type=null;
        }

        Page<AccumulatorProduct> page = accumulatorProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("type", "EQ", type,
                "brand", "EQ", brand,
                "pn", "EQ", pn),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }



    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delAccumulator(SimpleRequest request){
        List<AccumulatorProduct> accumulatorProducts = request.getA("del", AccumulatorProduct.class);
        for (AccumulatorProduct accumulatorProduct : accumulatorProducts) {
            accumulatorProductRepository.delete(accumulatorProduct);
        }
        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }


    /**
     * 添加
     * @param request
     * @return
     */
    public AccumulatorProduct insertAccumulator(SimpleRequest request){
        JSONObject jo = request.getJO();
        AccumulatorProduct accumulatorProduct  = jo.getObject("data",AccumulatorProduct.class);
        return accumulatorProductRepository.saveAndFlush(accumulatorProduct);
    }

    /**
     * 通过品牌+国际标号+参考号获取蓄电池标准商品
     * @param request
     * @return
     */
    public AccumulatorProduct getAccumulatorProduct(SimpleRequest request){
        JSONObject param = request.getJO();
        String brand = param.getString("brand");
        String grade = param.getString("grade");
        String reference = param.getString("reference");
        return accumulatorProductRepository.findByBrandAndGradeAndReference(brand, grade, reference);
    }

}
